package com.mk.settlement.controller;

import java.math.BigDecimal;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mk.settlement.model.SettlementRelation;
import com.mk.settlement.service.SettlementService;

@Controller
@RequestMapping("/sc/relation")
public class SettlementRelationController {

    private Logger log = LoggerFactory.getLogger(SettlementRelationController.class);

    @Resource
    private SettlementService settlementServiceImpl;

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public String insertRelation(Long settlementTargetId, String settlementTargetName, int settlementRuleId, String settlementThreshold) {

        log.info("添加酒店-规则对应关系...");
        log.info("输入参数:settlementTargetId=>" + settlementTargetId + ",settlementTargetName=>" + settlementTargetName + ",settlementRuleId=>"
                + settlementRuleId + ",settlementThreshold=>" + settlementThreshold);

        String result = null;
        SettlementRelation r = new SettlementRelation();

        r.setSettlementTargetId(settlementTargetId);
        r.setSettlementTargetName(settlementTargetName);
        r.setSettlementRuleId(settlementRuleId);

        if (settlementThreshold != null) {

            r.setSettlementThreshold(new BigDecimal(settlementThreshold).setScale(2));
        }

        try {
            int iResult = settlementServiceImpl.addSettlementRelation(r);
            if (iResult > 0) {
                result = "添加成功.";

                log.info("添加酒店-规则对应关系成功.");
            }
        } catch (DuplicateKeyException e) {
            log.info("酒店id:" + settlementTargetId + "已经存在规则settlementRuleId为" + settlementRuleId + "的对应关系.");
            result = "酒店id:" + settlementTargetId + "已经存在规则settlementRuleId为" + settlementRuleId + "的对应关系.";
        } catch (Exception e) {
            log.error("插入酒店规则对应关系异常!", e);
            result = "添加异常!";
        }

        return result;
    }

    @RequestMapping(value = "/init", method = RequestMethod.POST)
    @ResponseBody
    public String insertRelation(int ruleId) {

        log.info("从hotel表初始化酒店-规则对应关系...");
        
        return settlementServiceImpl.initRelation(ruleId);
    }
}
